package model

import (
	"fmt"
	"time"
	"turingApi/conf"
)

type AdLogs struct {
	Id      int       `xorm:"INT(11) PK AUTOINCR comment('主键')" json:"id"` //主键
	UserId  int       `xorm:"INT(11)" json:"user_id"`
	Status  bool      `xorm:"default false" json:"status"`
	Created time.Time `xorm:"DATETIME INDEX" json:"created"`
	Updated time.Time `xorm:"DATETIME" json:"updated"`
}

func (AdLogs) TableName() string {
	return "sys_ad_logs"
}

// GetAdLog SignGet 单条用户信息
func GetAdLog(uid int) (*AdLogs, bool) {

	//mods := make([]AdLogs, 0, 4)
	//sess := db.NewSession()
	//defer sess.Close()
	//
	//if uid > 0 {
	//	sess.Where("user_id = ?", uid)
	//}
	//sess.Where("status = ?", false)
	//sess.Where("TO_DAYS(created) = TO_DAYS(now()) ")
	//sess.Limit(1)
	//err := sess.Desc("id").Find(&mods)
	//return mods, err

	mod := &AdLogs{}
	has, _ := db.Where("user_id = ?", uid).
		Where("NOW() >= DATE_ADD(created, INTERVAL 10 SECOND)").
		Where("status = ?", false).
		Desc("created").
		Limit(1).
		Get(mod)
	conf.Logger.Info(fmt.Sprintf("数据： %v", mod))
	return mod, has
}

func GetTodayAds(uid int) ([]AdLogs, error) {
	mods := make([]AdLogs, 0, 4)
	sess := db.NewSession()
	defer sess.Close()

	if uid > 0 {
		sess.Where("user_id = ?", uid)
	}
	sess.Where("status = ?", true)
	sess.Where("TO_DAYS(created) = TO_DAYS(now()) ")
	err := sess.Desc("id").Find(&mods)
	return mods, err
}

func AdAdd(mod *AdLogs) error {
	sess := db.NewSession()
	defer sess.Close()
	sess.Begin()
	if _, err := sess.Insert(mod); err != nil {
		sess.Rollback()
		return err
	}
	sess.Commit()
	return nil
}

// AdEdit 编辑
func AdEdit(mod *AdLogs, cols ...string) error {
	sess := db.NewSession()
	defer sess.Close()
	sess.Begin()
	if _, err := sess.ID(mod.Id).Cols(cols...).Update(mod); err != nil {
		sess.Rollback()
		return err
	}
	sess.Commit()
	return nil
}
